package com.haierp.util.yitao;

/**
 * @Author: wwl
 * @Date: 2019/4/25 10:50
 * @Description:
 */



import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.IOException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RsaUtil {

    //将Base64编码后的公钥转换成PublicKey对象
    public static PublicKey string2PublicKey(String pubStr) throws Exception {
        byte[] keyBytes = base642Byte(pubStr);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    //将Base64编码后的私钥转换成PrivateKey对象
    public static PrivateKey string2PrivateKey(String priStr) throws Exception {
        byte[] keyBytes = base642Byte(priStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    //公钥加密
    public static byte[] publicEncrypt(byte[] content, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] bytes = cipher.doFinal(content);
        return bytes;
    }

    //私钥解密
    public static String privateDecrypt(byte[] content, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] bytes = cipher.doFinal(content);
        return new String(bytes);
    }

    //字节数组转Base64编码
    public static String byte2Base64(byte[] bytes) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }

    //Base64编码转字节数组
    public static byte[] base642Byte(String base64Key) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(base64Key);
    }

    /**
     * 加密
     * @param message
     * @param publicKeyStr
     * @return
     */
    public static String encryption(String publicKeyStr,String message)throws Exception{

            PublicKey publicKey = RsaUtil.string2PublicKey(publicKeyStr);
            //用公钥加密
            byte[] publicEncrypt = RsaUtil.publicEncrypt(message.getBytes(), publicKey);
            //加密后的内容Base64编码
            String byte2Base64 = RsaUtil.byte2Base64(publicEncrypt);
            return byte2Base64;

    }

    /**
     * 解密
     * @param PrivateKey
     * @param ciphertext
     * @return
     * @throws Exception
     */
    public static String decode(String PrivateKey,String ciphertext)throws Exception{
        PrivateKey privateKey = RsaUtil.string2PrivateKey(PrivateKey);
        //加密后的内容Base64解码
        byte[] base642Byte = RsaUtil.base642Byte(ciphertext);
        //用私钥解密
       String privateDecrypt = RsaUtil.privateDecrypt(base642Byte, privateKey);
       return privateDecrypt;
    }


    public static void main(String[] args) {
        //生成RSA公钥和私钥，并Base64编码
        String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCNQeTQimND0yxXTZX55drgIJOcdMtePMGku9SZ" +
                "DTlrTA4zJ208kWwwUJxgjVd8MdtvlWNB4PI0UpHbTav73c6WaP2HBDQpQzktKkx41Z6HeYINiHlQ" +
                "wO/ZT5W5Amia0k6325NOx6yPtu0+dW5bYcUbyOLLSv/9aEboK19xLGnhQwIDAQAB";
        String privateKeyStr="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAI1B5NCKY0PTLFdNlfnl2uAgk5x0" +
                "y148waS71JkNOWtMDjMnbTyRbDBQnGCNV3wx22+VY0Hg8jRSkdtNq/vdzpZo/YcENClDOS0qTHjV" +
                "nod5gg2IeVDA79lPlbkCaJrSTrfbk07HrI+27T51blthxRvI4stK//1oRugrX3EsaeFDAgMBAAEC" +
                "gYEAiQ56WO0tS03GJB8feYzQRc7V6mRYPmNs781fhfES2Uy+KlwC3VWsR2Svle8OB27Inweveugr" +
                "mSDUbJh8WrDoFA6eEvYrjSY/Nk3PWwHCNWJLtuHu1zIy1vgVI61XqAqdQV9LY8kPNMVM4g1n3uk6" +
                "kyeuIzWon4yp5QXkE53F9kECQQDKpsPL9gFezjMPrncTlzyDiXh5uChNu1tt9TfIppXj5ch3ds0e" +
                "FnQa3Ih5YfEDN30jiztDQJ5Xspg+Tni6Tm/LAkEAsnGd/K5qz9X/7exAVRDxPsmSJv/s8Vpc46fV" +
                "Onw4a/LpUVj2nx9/OZGPFcIgxWrdz7zgEPnCJTwKjWPVeis1aQJAKOpivdt9i1a2mIPxJtNyNFyd" +
                "JnY4LPmXDCxmhuybdtf+EaC66Ug/SO0d4OQVdUDO005ZOMrjLXGxq2LMnVEY4QJAEKfELEKHW7DI" +
                "u4dSld4H9mlQB+3ZSsm5Y9JVd6kChyjcGCiqlD2XXWM1rL0629JWs74YV91H/ru07G+GDGoeCQJA" +
                "QsCx5zmirqI91L/jvTTT2nesKR5CbfhIaG1X6oruYvz/2g/bor246RPa0xKj8sqAxhZ6xP8MwjfX" +
                "PqeUqKMw2Q==";
        try {
            //公钥加密
            String message = "123456";
            //将Base64编码后的公钥转换成PublicKey对象
            PublicKey publicKey = RsaUtil.string2PublicKey(publicKeyStr);
            //用公钥加密
            byte[] publicEncrypt = RsaUtil.publicEncrypt(message.getBytes(), publicKey);
            //加密后的内容Base64编码
            String byte2Base64 = RsaUtil.byte2Base64(publicEncrypt);
            System.out.println("公钥加密并Base64编码的结果：" + byte2Base64);
            //将Base64编码后的私钥转换成PrivateKey对象
            PrivateKey privateKey = RsaUtil.string2PrivateKey(privateKeyStr);
            //加密后的内容Base64解码
            byte[] base642Byte = RsaUtil.base642Byte(byte2Base64);
            //用私钥解密
            String privateDecrypt = RsaUtil.privateDecrypt(base642Byte, privateKey);
            //解密后的明文
            System.out.println("解密后的明文: " + privateDecrypt);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
